﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace WordStat.WordExceptions
{
    internal class WordExceptionService
    {
        public static void SetDirectory(string directory)
        {
            _filePath = Path.Combine(directory, FILE_NAME);
        }

        public void Load()
        {
            if (!File.Exists(_filePath))
                _wordExceptions = new WordExceptionRecordContainer();
            else
            {
                try
                {
                    var serializer = new XmlSerializer(typeof(WordExceptionRecordContainer));

                    using (var reader = new StreamReader(_filePath))
                    {
                        _wordExceptions = (WordExceptionRecordContainer)serializer.Deserialize(reader);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    _wordExceptions = new WordExceptionRecordContainer();
                }
            }
        }

        private void Save()
        {
            var listToSave = _wordExceptions.Records.Select(r => new WordExceptionRecord { Word = r.Word.ToLower() }).ToList();
            _wordExceptions.Records = listToSave;

            try
            {
                var root = new XmlRootAttribute("Records");

                var serializer = new XmlSerializer(typeof(WordExceptionRecordContainer));

                using (var writer = new StreamWriter(_filePath))
                {
                    serializer.Serialize(writer, _wordExceptions);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private WordExceptionRecordContainer _wordExceptions;

        public List<string> WordExceptions
        {
            get { return _wordExceptions.Records.Select(r => r.Word).ToList(); }
        }

        private static string _filePath;
        private const string FILE_NAME = "WordExceptions.xml";

        public void ShowWizard()
        {
            Load();

            var form = new EditWordExceptionForm();

            form.SetData(_wordExceptions);

            form.ShowDialog();

            Save();
        }
    }
}
